package njust.csc.aecore.utils

import java.nio.file.Path
import kotlin.io.path.exists
import kotlin.io.path.isDirectory
import kotlin.io.path.listDirectoryEntries
import kotlin.io.path.readText

/**
 * @Author ZhouHang
 * @Date 24/5/31 周五
 */
object RegexUtils {
    val urlMatch = "(\\b(https?)://|www\\.)[-A-Za-z0-9+&@#/%?=~_|!:,.;]*[-A-Za-z0-9+&@#/%=~_|]".toRegex()
    val ipMatch = "\\b((https?)://)?(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]?)\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b(?::\\b(6553[0-5]|655[0-2][0-9]|65[0-4][0-9]{2}|6[0-4][0-9]{3}|[1-5][0-9]{4}|[1-9][0-9]{0,3}))?".toRegex()
    val failReason = "\\[(.*)]".toRegex()  // adb install/uninstall 的错误信息
    val sdkName = "<(([a-zA-Z_][a-zA-Z0-9_]*[.])*([a-zA-Z_][a-zA-Z0-9_]*)):".toRegex()  // 用 soot 找到的
    val numberInFileName = "(?<=-)\\d+".toRegex()

    /**
     * 搜索目录下的所有文件，搜索匹配的字符串
     * @param dir 待搜索的路径
     * @param results 匹配成功字符串保存位置
     * @param pattern 正则表达式
     * */
    fun searchFileRecv(dir: Path, results: MutableList<String>, pattern: Regex) {
        if (!dir.exists())
            return
        for (son in dir.listDirectoryEntries()) {
            if (son.isDirectory()) {
                searchFileRecv(son, results, pattern)
            } else {
                results.addAll(searchString(pattern, son.readText()))
            }
        }
    }

    /**
     * 根据正则表达式搜索 text
     * @param pattern 正则表达式
     * @param text 待匹配的字符串
     * */
    fun searchString(pattern: Regex, text: String): List<String> {
        val matchResults = pattern.findAll(text)
        val list = mutableListOf<String>()
        for (result in matchResults) {
            list.add(result.value)
        }
        return list.toList()
    }
}
